package com.example.testproj.ipc;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.testproj.R;

public class IpcTestActivity extends AppCompatActivity {
    private Messenger messenger;
    private Messenger replayMessenger;
    private MyHandler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipc_test);

        bindService(new Intent(this,IpcTestService.class),serviceConnection,BIND_AUTO_CREATE);
        myHandler=new MyHandler();
        replayMessenger=new Messenger(myHandler);
    }
    private ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            messenger=new Messenger(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    public void click(View view) {
        try{
            if (view.getId()==R.id.button5){
                Message message=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("word","哈哈哈哈，你好啊");
               // message.obj="哈哈哈哈，你好啊";
                message.setData(bundle);
                message.replyTo=replayMessenger;
                messenger.send(message);
            }else if (view.getId()==R.id.button6){

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public static class MyHandler extends Handler{
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            Log.d("qin","收到回复消息"+msg.getData().getString("word"));
        }
    }
}
